#include "mplayer.h"

struct music *p;
int mustarmark=0;
char music[4096+32];

//音乐盒初始化
struct music *music_init()
{
	struct music *head=malloc(sizeof(struct music));
	head->next=NULL;
	head->prev=NULL;
	return head;
}

//音乐盒存储音乐
void music_install(struct music *head,char music_name[100],char music_path[4096])
{
	struct music *newmusic=malloc(sizeof(struct music));
	newmusic->next=NULL;
	newmusic->prev=NULL;
	strcpy(newmusic->music_name,music_name);
	strcpy(newmusic->music_path,music_path);
	struct music *p=head;
	while(p->next!=NULL)
	{
		p=p->next;
	}
	newmusic->prev=p;
	p->next=newmusic;
}

//展示歌曲列表
void music_show(struct music *head)
{
	struct music *print=head->next;   //定义一个指针跳过头结点指向头结点的下一个结点
	while(print!=NULL)                     //遍历单链表，如果当前结点不为空，则打印当前结点数据并移动指针到下一个结点
	{
		printf(BOLD CYAN"%s\n"RESET,print->music_name);
		print=print->next;
	}
}

//销毁双向链表
void broke_music(struct music *head)                        
{
	struct music *p=head;                                  //定义一个指针指向头结点
	struct music *next=NULL;                               //再定义一个指针暂时指向空
	while(p!=NULL)                                              //如果当前结点不为空
	{
		next=p->next;                                           //next指针指向下一个结点
		free(p);                                                //释放当前结点
		p=next;	                                                //将p指针移向下一个结点
	}
}

int music_add(struct music *head,char music_path[4096])
{
	DIR *mydir;
	struct dirent *dit;
	char all_path[4096];
	mydir=opendir(music_path);
	bzero(all_path,4096);
	if(mydir==NULL)
	{
		perror("目录打开失败！\n");
		return -1;
	}
	while(1)
	{
		dit=readdir(mydir);
		if(errno==0&&dit==NULL)
			break;
		if (dit->d_name[0] == '.')
            continue;
		if (!strstr(dit->d_name, ".mp3"))
            continue;
		snprintf(all_path, sizeof(all_path), "%s/%s", music_path, dit->d_name);
		music_install(head,dit->d_name,all_path);
	}
	return 0;
}

void music_start(struct music *head)
{
	p=head;
	while(p->prev!=head)
		p=p->next;
	sprintf(music,"mplayer %s &",p->music_path);
	system(music);
	mustarmark=1;
}

void music_stop()
{
	system("killall -STOP mplayer");
}

void music_continue()
{
	system("killall -CONT mplayer");
}

void music_next()
{
	if(p->next==NULL&&mustarmark==1)
		printf(BOLD YELLOW"到尾啦！\n"RESET);
	if(mustarmark==1&&p->next!=NULL)
	{
		system("killall -9 mplayer");
		p=p->next;
		printf(BOLD YELLOW"现在播放的是：%s\n"RESET,p->music_name);
		sprintf(music,"mplayer %s &",p->music_path);
		system(music);
	}
}

void music_prev(struct music *head)
{
	if(p==head->next&&mustarmark==1)
		printf("到头啦！\n");
	if(mustarmark==1&&p!=head->next)
	{
		system("killall -9 mplayer");
		p=p->prev;
		printf(BOLD YELLOW"现在播放的是：%s\n"RESET,p->music_name);
		sprintf(music,"mplayer %s &",p->music_path);
		system(music);
	}
}

void music_over(struct music *head)
{
	system("killall mplayer");
	broke_music(head);
}

